package com.zxl.always.on.display.ui.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

/**
 * 监听home键，必须在当前界面运行时注册，运行结束后反注册
 * @author zhanghuijun
 *
 */
public class HomeKeyMonitor {

	/**
	 * 参数
	 */
	private static final String SYSTEM_REASON = "reason";
	private static final String SYSTEM_HOME_KEY = "homekey";
	private static final String SYSTEM_HOME_RECENT_APPS = "recentapps";
	private static final String SYSTEM_HOME_LOCK = "lock";
	/**
	 * 监听home键的Receiver
	 */
	private BroadcastReceiver mHomeKeyReceiver = null;
	/**
	 * Context
	 */
	private Context mContext = null;
	/**
	 * OnHomeKeyListener
	 */
	private OnHomeKeyListener mOnHomeKeyListener = null;
	
	/**
	 * @param context
	 */
	public HomeKeyMonitor(Context context, OnHomeKeyListener onHomeKeyListener) {
		mContext = context;
		mOnHomeKeyListener = onHomeKeyListener;
		if (mHomeKeyReceiver == null) {
			mHomeKeyReceiver = new BroadcastReceiver() {

				@Override
				public void onReceive(Context context, Intent intent) {
					if (null == intent) {
						return;
					}
					String action = intent.getAction();
					if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
						String reason = intent.getStringExtra(SYSTEM_REASON);
						if (!TextUtils.isEmpty(reason)) {
							if (reason.equals(SYSTEM_HOME_KEY)) {
								// home键
								if (mOnHomeKeyListener != null) {
									mOnHomeKeyListener.onHome();
								}
							} else if (reason.equals(SYSTEM_HOME_RECENT_APPS)) {
								// 最近应用
								if (mOnHomeKeyListener != null) {
									mOnHomeKeyListener.onRecentApps();
								}
							} else if (reason.equals(SYSTEM_HOME_LOCK)) {
								// 最近应用
								if (mOnHomeKeyListener != null) {
									mOnHomeKeyListener.onLock();
								}
							} 
						}
					} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
						if (mOnHomeKeyListener != null) {
							mOnHomeKeyListener.onLock();
						}
					}
				}
			};
		}
		IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		filter.addAction(Intent.ACTION_USER_PRESENT);
		context.registerReceiver(mHomeKeyReceiver, filter);
	}
	
	public void unregisterReceiver() {
		if (mHomeKeyReceiver != null) {
			mContext.unregisterReceiver(mHomeKeyReceiver);
			mHomeKeyReceiver = null;
		}
	}
}
